import { useState, useEffect } from 'react';
import { Card, Table, Space, Button, Input, Popconfirm, Divider, Modal } from 'antd';
import { SyncOutlined, PlusOutlined } from '@ant-design/icons';
import { connect, FormattedMessage, useIntl } from 'umi';
import EmpEdit from './empEdit';
import request from '@/utils/request';

const currControl = 'Employee';
const apiURL = '/api/services/app/Employee/';
const { Search } = Input;

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [visible, setVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [keywords, setKeywords] = useState('');
  const [record, setRecord] = useState<any>({});
  const intl = useIntl();

  useEffect(() => {
    fetchDatas();
  }, [pageIndex, keywords]);

  const fetchDatas = () => {
    setVisible(false);
    setLoading(true);
    request(apiURL + 'GetList', {
      method: 'GET',
      params: { SkipCount: (pageIndex - 1) * pageSize, MaxResultCount: pageSize, keywords },
    }).then((response) => {
      if (response) {
        if (response.success) {
          setDataSource(response.result.items);
          setTotalCount(response.result.totalCount);
        }
        setLoading(false);
      }
    });
  };

  const handleDelete = (id: number) => {
    const {dispatch} = props;
    dispatch({
        type: 'Abp/delete',
        payload: { id },
        control: currControl,
      })
      .then(() => {
        fetchDatas();
      });
  };

  const onSelectChange = (selectedRowKeys: any) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const onSearch = (keywords: any) => {
    setKeywords(keywords);
  };

  const swithDrawer = (visible: boolean, record = null) => {
    setVisible(visible);
    setRecord(record);
  };

  const columns = [
    {
      title: <FormattedMessage id="pages.empNum" />,
      dataIndex: 'empNum',
    },
    {
      title: <FormattedMessage id="pages.empName" />,
      dataIndex: 'empName',
    },    
    {
      title: <FormattedMessage id="pages.department" />,
      render: (record: any) => <span>{record.tDepartment?.deptName}</span>,
    },
    {
      title: <FormattedMessage id="pages.operation" />,
      render: (record: any) =>
        dataSource.length >= 1 ? (
          <span>
            <Popconfirm
              title={<FormattedMessage id="pages.delete.confirm" />}
              onConfirm={() => handleDelete(record.id)}
            >
              <a>
                <FormattedMessage id="pages.delete" />
              </a>
            </Popconfirm>
            <Divider type="vertical" />
            <a onClick={() => swithDrawer(true, record)}>
              <FormattedMessage id="pages.edit" />
            </a>
          </span>
        ) : null,
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  return (
    <div>
      <Card>
        <Space>
          <Button
            type="primary"
            onClick={fetchDatas}
            loading={loading}
            icon={<SyncOutlined />}
          >
            <span>
              <FormattedMessage id="pages.refresh" />
            </span>
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => swithDrawer(true)}>
            <span>
              <FormattedMessage id="pages.new" />
            </span>
          </Button>
          <Search
            style={{ width: 240 }}
            placeholder={intl.formatMessage({id: 'pages.enterKeywords'})}
            onSearch={(value) => onSearch(value)}
          />
        </Space>
      </Card>
      <Table
        rowKey="id"
        loading={loading}
        rowSelection={rowSelection}
        columns={columns}
        dataSource={dataSource}
        pagination={{
          onChange: (page) => {
            setPageIndex(page);
          },
          pageSize,
          total: totalCount,
        }}
      />
      <Modal
        title={<FormattedMessage id="pages.employeeEdit" />}
        visible={visible}
        destroyOnClose={true}
        onCancel={() => swithDrawer(false)}
        footer={false}
        closable
      >
        <EmpEdit ParentData={record} fetchDatas={fetchDatas} />
      </Modal>
    </div>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
